package com.sttk.secreconeclick.bookkeep.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.lzb.basic.utils.SPUtil;
import com.sttk.secreconeclick.bookkeep.BaseAc;
import com.sttk.secreconeclick.bookkeep.Content;
import com.sttk.secreconeclick.bookkeep.R;
import com.sttk.secreconeclick.bookkeep.adapter.SearchAdapter;
import com.sttk.secreconeclick.bookkeep.bean.AccountBookBean;
import com.sttk.secreconeclick.bookkeep.bean.BillBean;
import com.sttk.secreconeclick.bookkeep.databinding.ActivitySearchBinding;
import com.sttk.secreconeclick.bookkeep.utils.AppSpUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SearchActivity extends BaseAc<ActivitySearchBinding> implements View.OnClickListener {

    private SearchAdapter searchAdapter;
    private List<BillBean> listAll = new ArrayList<>();
    private List<BillBean> searchResults = new ArrayList<>();
    private int searchType = 0; // 0: 类别, 1: 备注, 2: 金额
    private int sortType = 0; // 0: 按时间降序, 1: 按金额绝对值降序

    @Override
    protected int onCreate() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {
        mDataBinding.ivSrearchBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.tvType.setOnClickListener(this);
        mDataBinding.tvRemark.setOnClickListener(this);
        mDataBinding.tvMoney.setOnClickListener(this);
        mDataBinding.tvSearch.setOnClickListener(this);
        mDataBinding.tvByTime.setOnClickListener(this);
        mDataBinding.tvByMoney.setOnClickListener(this);

        mDataBinding.rvBillList.setLayoutManager(new LinearLayoutManager(mContext));
        searchAdapter = new SearchAdapter();
        mDataBinding.rvBillList.setAdapter(searchAdapter);
    }

    @Override
    protected void initData() {
        getData();
        // 初始显示所有数据
        searchResults = new ArrayList<>(listAll);
        sortData();
        if (searchResults != null && searchResults.size() > 0) {
            searchAdapter.setList(searchResults);
            mDataBinding.llSearchResult.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.llSearchResult.setVisibility(View.GONE);
        }
    }

    private void getData() {
        AccountBookBean accountBookBean = AppSpUtils.getAccountBookList().get(SPUtil.getInt(mContext, Content.accountBook, 0));
        listAll = accountBookBean.getBillBeanList();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tvType) {
            // 类别搜索
            searchType = 0;
            updateSearchTypeUI();
        } else if (id == R.id.tvRemark) {
            // 备注搜索
            searchType = 1;
            updateSearchTypeUI();
        } else if (id == R.id.tvMoney) {
            // 金额搜索
            searchType = 2;
            updateSearchTypeUI();
        } else if (id == R.id.tvSearch) {
            // 执行搜索
            performSearch();
        } else if (id == R.id.tvByTime) {
            // 按时间排序
            sortType = 0;
            updateSortUI();
            sortData();
        } else if (id == R.id.tvByMoney) {
            // 按金额排序
            sortType = 1;
            updateSortUI();
            sortData();
        }
    }

    private void updateSearchTypeUI() {
        // 重置所有搜索类型按钮样式
        mDataBinding.tvType.setBackgroundColor(searchType == 0 ? Color.parseColor("#FFFFFF") : Color.parseColor("#00FFFFFF"));
        mDataBinding.tvRemark.setBackgroundColor(searchType == 1 ? Color.parseColor("#FFFFFF") : Color.parseColor("#00FFFFFF"));
        mDataBinding.tvMoney.setBackgroundColor(searchType == 2 ? Color.parseColor("#FFFFFF") : Color.parseColor("#00FFFFFF"));

        // 更新提示文本
        if (searchType == 0) {
            mDataBinding.etInput.setHint(getString(R.string.input_type));
        } else if (searchType == 1) {
            mDataBinding.etInput.setHint(getString(R.string.input_remark));
        } else if (searchType == 2) {
            mDataBinding.etInput.setHint(getString(R.string.input_money));
        }
    }

    private void updateSortUI() {
        // 更新排序按钮样式
        mDataBinding.tvByTime.setBackgroundResource(sortType == 0 ? R.drawable.orange_18_dp : R.drawable.white_18_dp);
        mDataBinding.tvByTime.setTextColor(sortType == 0 ? Color.parseColor("#FFFFFF") : Color.parseColor("#323433"));
        mDataBinding.tvByMoney.setBackgroundResource(sortType == 1 ? R.drawable.orange_18_dp : R.drawable.white_18_dp);
        mDataBinding.tvByMoney.setTextColor(sortType == 1 ? Color.parseColor("#FFFFFF") : Color.parseColor("#323433"));
    }

    private void performSearch() {
        String input = mDataBinding.etInput.getText().toString().trim();
        if (TextUtils.isEmpty(input)) {
            // 输入为空时显示所有数据
            searchResults = new ArrayList<>(listAll);
        } else {
            searchResults.clear();

            if (searchType == 0) {
                // 按类别搜索
                for (BillBean billBean : listAll) {
                    if (billBean.getBillTypeBean() != null &&
                            billBean.getBillTypeBean().getName() != null &&
                            billBean.getBillTypeBean().getName().toLowerCase().contains(input.toLowerCase())) {
                        searchResults.add(billBean);
                    }
                }
            } else if (searchType == 1) {
                // 按备注搜索
                for (BillBean billBean : listAll) {
                    if (billBean.getRemark() != null &&
                            billBean.getRemark().toLowerCase().contains(input.toLowerCase())) {
                        searchResults.add(billBean);
                    }
                }
            } else if (searchType == 2) {
                // 按金额搜索（大于等于输入金额）
                try {
                    double money = Double.parseDouble(input);
                    if (money <= 0) {
                        ToastUtils.showShort("金额必须大于0");
                        return;
                    }

                    for (BillBean billBean : listAll) {
                        if (Math.abs(billBean.getMoney()) >= money) {
                            searchResults.add(billBean);
                        }
                    }
                } catch (NumberFormatException e) {
                    ToastUtils.showShort("请输入有效的金额数字");
                    return;
                }
            }
        }

        sortData();
        searchAdapter.setList(searchResults);

        if (searchResults.isEmpty()) {
            mDataBinding.llSearchResult.setVisibility(View.GONE);
            ToastUtils.showShort("未找到匹配的数据");
        } else {
            mDataBinding.llSearchResult.setVisibility(View.VISIBLE);
        }
    }

    private void sortData() {
        if (searchResults == null || searchResults.isEmpty()) {
            return;
        }

        if (sortType == 0) {
            // 按时间降序排序
            Collections.sort(searchResults, new Comparator<BillBean>() {
                @Override
                public int compare(BillBean b1, BillBean b2) {
                    return Long.compare(b2.getDate(), b1.getDate()); // 降序
                }
            });
        } else if (sortType == 1) {
            // 按金额绝对值降序排序
            Collections.sort(searchResults, new Comparator<BillBean>() {
                @Override
                public int compare(BillBean b1, BillBean b2) {
                    return Double.compare(Math.abs(b2.getMoney()), Math.abs(b1.getMoney())); // 降序
                }
            });
        }
        searchAdapter.setList(searchResults);
    }

}